﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Configuration;
using System.Windows.Input;
using RG.Common.Configuration;
using RG.Common.Export;
using RG.Common.WPF.Commands;
using RG.Common.WPF.Dialogs;
using Microsoft.Practices.Unity;
using RG.Common;

namespace RG.Common.WPF.BaseFrame
{
    [SupportDataBinding]
    public class GridVM<T>
    {
        [Dependency]
        public IUnityContainer Cfg { get; set; }

        [Dependency]
        public IWorkplace Workplace { get; set; }

        public ICommand ColumnPresetEditCmd { get; set; }

        public ObservableCollection<IColumnInfo> Columns { get; set; }

        private ObservableCollection<T> items;
        
        public ObservableCollection<T> Items
        {
            get { return items; }
            set
            {
                items = value;
                if(items!=null)
                    items.CollectionChanged += CollectionChanged;
                if(ItemsChanged!=null)
                    ItemsChanged();
            }
        }

        private void CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if(ItemsChanged!=null)
                ItemsChanged();
        }

        private T selectedItem;
        public T SelectedItem
        {
            get { return selectedItem; }
            set
            {
                selectedItem = value;
                if(SelectedItemChanged!=null)
                    SelectedItemChanged();
            }
        }

        public Action ItemsChanged { get; set; }
        public Action SelectedItemChanged { get; set; }

        [PropertySetting(SaveNullValue = true, SerializeAs = SettingsSerializeAs.Xml)]
        public List<ColumnPreset> ColumnPreset { get; set; }

        public GridVM()
        {
            ColumnPresetEditCmd = new DelegateCommand(DoColumnsPresetEdit);
        }

        public void DoColumnsPresetEdit()
        {
            var itemVM = Cfg.Resolve<ColumnDataGridPresetDialogVM>();
            itemVM.Item = ColumnPreset;
            if (Workplace.ShowEditableDialog(itemVM, String.Format("Настройки таблицы")))
            {
                ColumnPreset = itemVM.Item;
            }
        }
    }
}
